//
//  CZOAuthViewController.swift
//  Blog
//
//  Created by whitcast on 16/7/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//导入第三方框架
import SVProgressHUD
import AFNetworking
//
let WeiboAppKey = "1747767486"
// 微博appsecret
let WeiboAppSecret = "a42ea3fdaed503c71e845973c2271bc0"
//微博授权回调页
let WeiboRedirect_Uri = "http://www.baidu.com"

class CZOAuthViewController: UIViewController {
    // MARK: --懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //自定义视图
        webView.delegate = self
         //  默认不透明,改成透明
        webView.opaque = false
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupNavUI()
        requestOAuthLogin()
    }
    
    private func requestOAuthLogin() {
        //  请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        print(url)
        //  准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //  加载请求
        webView.loadRequest(request)
    }
    
    private func setupNavUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "一键填写", target: self, action: "autoFillAction")
    }
    // MARK: -- 点击事件
    @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        print("一键填写")
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '247819230@qq.com'; document.getElementById('passwd').value = 'llz615614$'")
    }
    
    // 通过授权码(code)获取accesstoken
//    private func requestAccesstoken(code: String){
//        
//        CZNetworkTools.sharedTools.requestAccesstoken(code) { (response, error) -> () in
//            if error != nil {
//                print(error)
//                return
//            }
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确的json格式")
//                return
//            }
//            
//            let userAccount = CZUserAccount(dic: dic)
//            
//            print(userAccount)
//            
//            //  通过accessToken和uid获取用户信息
//            self.requestUserInfo(userAccount)
//            
//            
//        }
//    }
    // 获取有用信息
//    private func requestUserInfo(userAccount: CZUserAccount) {
//    
//        CZNetworkTools.sharedTools.requestUserInfo(userAccount) { (response, error) -> () in
//            
//            if error != nil {
//                print(error)
//                return
//            }
//            guard let dic = response as? [String: AnyObject] else {
//                print("不是一个正确json格式")
//                return
//            }
//            //代码执行到此字典一定有值
//            let name = dic["name"]
//            let avatar_large = dic["avatar_large"]
//            
//            //设置用户名和头像
//            userAccount.name = name as? String
//            userAccount.avatar_large = avatar_large as? String
//            // 保护用户对象
//            userAccount.saveUserAccount()
//            print(userAccount)
//        }
//    }
//    
    
}

extension CZOAuthViewController: UIWebViewDelegate{
    //将要加载的请求 
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            return false
        }
        // 代码执行到此，我们的url一定有值
        // 获取url的绝对地址
      
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        print(url.absoluteString)
        // 代码执行到此我们需要关心的url字符串
        if let query = url.query where query.hasPrefix("code=") {
            //截取code
            let code = query.substringFromIndex("code=".endIndex)
            print("我想要的code: " + code)
//            requestAccesstoken(code)
            CZUserAccountViewModel.shareUserAccount.requestAccesstoken(code, callBack: { (isSuccess) -> () in
                if isSuccess {
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //  发送通知,释放资源
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                    
                    
                }else {
                    print("登录失败")
                }
            })
            
        }else {
            // 取消进入回调页
            dismissViewControllerAnimated(true, completion: nil)
        }
        return false
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
}

